package com.yonyou.pmclouds.team.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.ChineseStringUtils;
import com.yonyou.pmclouds.businessobject.util.SortListUtil;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseVO;
import com.yonyou.pmclouds.enterprise.rmiitf.EnterpriseQuery;
import com.yonyou.pmclouds.outter.enterprise.EnterpriseInfoQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.personnel.entity.PersonnelVO;
import com.yonyou.pmclouds.personnel.rmiitf.PersonnelQuery;
import com.yonyou.pmclouds.team.entity.*;
import com.yonyou.pmclouds.team.rmiitf.TeamEnterpriseQuery;
import com.yonyou.pmclouds.team.rmiitf.TeamMemberMaintain;
import com.yonyou.pmclouds.team.rmiitf.TeamMemberQuery;
import com.yonyou.pmclouds.user.entity.UserInfo;
import com.yonyou.pmclouds.user.entity.UserSearchResultVO;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping({"/mobile/team"})
public class TeamMobController {

    @Autowired
    private UserInfoQuery userInfoQuery;

    @Autowired
    private EnterpriseInfoQuery enterpriseInfoQuery;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamMemberQuery memberQuery;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamMemberMaintain memberMaintain;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamEnterpriseQuery enterpriseQuery;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private EnterpriseQuery ygcEnterpriseQuery;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private PersonnelQuery personnelQuery;

    @Value("${pmcloud.useNewProjectTeamTenant}")
    private String useNewTeamTenantIds;

    /**
     * 是否使用新版本的项目团队，false继续使用原有接口
     */
    @RequestMapping("/isUseNewTeam")
    public boolean isUseNewTeam() {
        boolean flag = false;
        String tenantId = RuntimeEnvironment.getTenantId();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(useNewTeamTenantIds) && useNewTeamTenantIds.contains(tenantId)) {
            flag = true;
        }

        return flag;
    }

    @GetMapping("/members")
    public TeamMemberVO[] getMembers(@RequestParam("projectid") String projectid) throws BusinessException {
        TeamMemberVO[] teamMembers = memberQuery.queryByProject(projectid);

        if(teamMembers == null || teamMembers.length <= 0){
            return new TeamMemberVO[0];
        }

        userInfoQuery.tranUserInfoField(teamMembers, new String[]{TeamMemberVO.PK_USER}, new String[]{TeamMemberVO.USER_NAME});

        List<TeamMemberVO> sortMemberList = Arrays.asList(teamMembers);
        SortListUtil.sort(sortMemberList, TeamMemberVO.USER_NAME, SortListUtil.ASC);

        return sortMemberList.toArray(new TeamMemberVO[]{});
    }

    @GetMapping("/constructionUnits")
    public TeamEnterpriseRefVO[] getConstructionUnit(@RequestParam("projectid") String projectid) throws BusinessException {
        TeamEnterpriseRefVO[] result = enterpriseQuery.queryConstructionUnitInProject(projectid);
//        enterpriseInfoQuery.tranEntInfoField(result, new String[]{TeamEnterpriseVO.PK_ENTERPRISE}, new String[]{TeamEnterpriseVO.ENTERPRISE_NAME});
        return result;
    }

    /**
     * 监理单位
     */
    @GetMapping("/supervisionUnits")
    public TeamEnterpriseRefVO[] getSupervisionUnit(@RequestParam("projectid") String projectid) throws BusinessException {
        TeamEnterpriseRefVO[] result = enterpriseQuery.querySupervisionUnitInProject(projectid);
//        enterpriseInfoQuery.tranEntInfoField(result, new String[]{TeamEnterpriseVO.PK_ENTERPRISE}, new String[]{TeamEnterpriseVO.ENTERPRISE_NAME});
        return result;
    }

    /**
     * 查询项目的所有参与企业
     *
     * @param projectid
     * @return
     * @throws BusinessException
     */
    @GetMapping("/enterpriseOfProject")
    public TeamEnterpriseViewVO[] getEnterpriseOfProject(@RequestParam("projectid") String projectid) throws BusinessException {
        TeamEnterpriseViewVO[] result = enterpriseQuery.queryEnterpriseViewVOsByProject(projectid);

        if (ArrayUtils.isEmpty(result)) {
            return result;
        }

        if(isUseNewTeam()){
            setEnterpriseAndUserInfo(result);
        }else{
            //设置参与企业名称
            enterpriseInfoQuery.tranEntInfoField(result, new String[]{TeamEnterpriseVO.PK_ENTERPRISE},
                    new String[]{TeamEnterpriseVO.ENTERPRISE_NAME});

            //设置参与人员用户名、电话和邮箱
            for (TeamEnterpriseViewVO ent : result) {
                setMembersInfo(ent);
            }
        }

        List<TeamEnterpriseViewVO> sortEnterpriseVOS = Arrays.asList(result);

        SortListUtil.sort(sortEnterpriseVOS, new String[]{TeamEnterpriseVO.ENTERPRISE_NAME, TeamEnterpriseVO.ENT_ROLE},
                new String[]{SortListUtil.ASC, SortListUtil.ASC});

        return sortEnterpriseVOS.toArray(new TeamEnterpriseViewVO[]{});
    }

    private void setEnterpriseAndUserInfo(TeamEnterpriseViewVO[] result) throws BusinessException {
        List<String> pkEnterpriseList = new ArrayList<>();
        List<String> pkUserList = new ArrayList<>();
        for(TeamEnterpriseViewVO teamEnterpriseViewVO : result){
            pkEnterpriseList.add(teamEnterpriseViewVO.getPkEnterprise());

            TeamMemberViewVO[] teamMemberViewVOs = teamEnterpriseViewVO.getTeamMemberViewVOs();
            if(teamMemberViewVOs == null || teamMemberViewVOs.length <= 0){
                continue;
            }

            for(TeamMemberViewVO teamMemberViewVO : teamMemberViewVOs){
                pkUserList.add(teamMemberViewVO.getPkUser());
            }
        }

        Map<String, EnterpriseVO> enterpriseVOMap = new HashMap<>();
        EnterpriseVO[] enterpriseVOS = ygcEnterpriseQuery.queryByIds(pkEnterpriseList.toArray(new String[]{}));
        if(enterpriseVOS != null && enterpriseVOS.length > 0){
            for(EnterpriseVO enterpriseVO : enterpriseVOS){
                enterpriseVOMap.put(enterpriseVO.getPkEnterprise(), enterpriseVO);
            }
        }

        Map<String, PersonnelVO> personnelVOMap = new HashMap<>();
        PersonnelVO[] personnelVOS = personnelQuery.queryByUserIds(pkUserList.toArray(new String[]{}));
        if(personnelVOS != null && personnelVOS.length > 0){
            for(PersonnelVO personnelVO : personnelVOS){
                personnelVOMap.put(personnelVO.getUserId(), personnelVO);
            }
        }

        for(TeamEnterpriseViewVO teamEnterpriseViewVO : result){
            EnterpriseVO enterpriseVO = enterpriseVOMap.get(teamEnterpriseViewVO.getPkEnterprise());
            if(enterpriseVO != null){
                teamEnterpriseViewVO.setEnterpriseName(enterpriseVO.getName());
            }

            TeamMemberViewVO[] teamMemberViewVOs = teamEnterpriseViewVO.getTeamMemberViewVOs();
            if(teamMemberViewVOs == null || teamMemberViewVOs.length <= 0){
                continue;
            }

            for(TeamMemberViewVO teamMemberViewVO : teamMemberViewVOs){
                PersonnelVO personnelVO = personnelVOMap.get(teamMemberViewVO.getPkUser());
                if(personnelVO != null){
                    teamMemberViewVO.setPhoneNo(personnelVO.getPhone());
                    teamMemberViewVO.setEmail(personnelVO.getEmail());
                    teamMemberViewVO.setUserName(personnelVO.getUserName());
                    teamMemberViewVO.setEnterpriseName(enterpriseVO == null ? "" : enterpriseVO.getName());
                }
            }
        }
    }

    /**
     * 判断用户是否属于，当前项目的项目团队中的施工方。
     */
    @RequestMapping("/isConstructor")
    public Boolean isConstructor(@RequestParam("pkProject") String pkProject, @RequestParam("pkUser") String pkUser) throws BusinessException {
        if (StringUtils.isEmpty(pkProject) || StringUtils.isEmpty(pkUser)) {
            return false;
        }
        TeamMemberVO[] teamMemberVOS = memberQuery.queryByProAndPkUsers(pkProject, new String[]{pkUser});
        if (ArrayUtils.isEmpty(teamMemberVOS) || teamMemberVOS[0] == null) {
            return false;
        }
        return teamMemberVOS[0].getUserRole() != null && teamMemberVOS[0].getUserRole() == TeamMemberVO.UserRoleConst.ROLE_CONSTRUCTOR;
    }

    /**
     * 获取当前用户所在项目的角色，默认为施工️方
     */
    @RequestMapping("/roleInProject")
    public TeamMemberVO userRoleInProject(@RequestParam("pkProject") String pkProject) throws BusinessException {
        if (StringUtils.isEmpty(pkProject)) {
            return null;
        }
        TeamMemberVO[] teamMemberVOS = memberQuery.queryByProAndPkUsers(pkProject, new String[]{RuntimeEnvironment.getLoginUserId()});
        if (ArrayUtils.isEmpty(teamMemberVOS) || teamMemberVOS[0] == null) {
            return null;
        }
        return teamMemberVOS[0];
    }

    @RequestMapping("/searchUser")
    public UserSearchResultVO.ContentVO searchUserForTeam(@RequestParam(value = "keyword", required = false) String keyword,
                                                          @RequestParam("tenantId") String tenantId,
                                                          @RequestParam("entId") String entId,
                                                          @RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,
                                                          @RequestParam("projectId") String projectId) throws BusinessException {
        // 查询当前团队的该企业的成员
        TeamMemberVO[] teamMemberVOS = memberQuery.queryByProject(projectId);
        String[] members = {};
        if (ArrayUtils.isNotEmpty(teamMemberVOS)) {
            members = new String[teamMemberVOS.length];
            for (int i = 0; i < teamMemberVOS.length; i++) {
                members[i] = teamMemberVOS[i].getPkUser();
            }
        }
        RuntimeEnvironment.setTenantId(tenantId);
        return userInfoQuery.searchUsersByEnterId(keyword, entId, pageNum, pageSize, members);
    }

    @PostMapping("/addMembers")
    public int addMember(@RequestBody MemberAddVO memberAddVO) throws BusinessException {
        if (ArrayUtils.isEmpty(memberAddVO.getUsers())) {
            return 0;
        }
        // TODO 可能需要权限校验
        // 查询企业信息
        TeamEnterpriseVO[] teamEnterpriseVOS = enterpriseQuery.queryByProject(memberAddVO.projectId);
        if (ArrayUtils.isEmpty(teamEnterpriseVOS)) {
            return 0;
        }
        TeamEnterpriseVO ent = null;
        for (TeamEnterpriseVO teamEnterpriseVO : teamEnterpriseVOS) {
            if (teamEnterpriseVO.getPkEnterprise().equals(memberAddVO.entId)) {
                ent = teamEnterpriseVO;
                break;
            }
        }
        if (ent == null) {
            return 0;
        }
        // 构造成员信息
        List<TeamMemberVO> members = new ArrayList<>(memberAddVO.users.length);
        for (String user : memberAddVO.users) {
            TeamMemberVO member = new TeamMemberVO();
            member.setPkEnterprise(memberAddVO.entId);
            member.setPkProject(memberAddVO.projectId);
            member.setPkTenant(ent.getPkTenant());
            member.setUserRole(ent.getEntRole());
            member.setPkUser(user);
            members.add(member);
        }
        memberMaintain.addMembers(members.toArray(new TeamMemberVO[0]));
        return 0;
    }

    @PostMapping("/removeMember")
    public String removeMember(@RequestBody TeamMemberVO memberVO) throws BusinessException {
        return memberMaintain.removeFromTeam(memberVO.getPkTeamMember(), memberVO.getChangeFlag());
    }

    /**
     * 返回制单人施工单位
     */
    @RequestMapping(value = "/getConstructEnterprise")
    @ResponseBody
    public Map<String, String> getConstructEnterprise(@RequestParam("pkProject") String pkProject) throws BusinessException {
        String[] keys = new String[]{"pkEnterprise", "enterpriseName"};
        Map<String, String> result = new HashMap<>();
        String creator = RuntimeEnvironment.getLoginUserId();
        TeamMemberVO[] teamMemberVOS = memberQuery.queryByProject(pkProject);
        if(ArrayUtils.isNotEmpty(teamMemberVOS)){
            //企业信息添加
            enterpriseInfoQuery.tranEntInfoField(teamMemberVOS, new String[]{TeamMemberVO.PK_ENTERPRISE}, new String[]{TeamMemberVO.ENTERPRISE_NAME});

            for(TeamMemberVO vo : teamMemberVOS){
                if(vo == null || vo.getUserRole() == null || vo.getUserRole() != TeamEnterpriseVO.EnterpriseRoleConst.ROLE_CONSTRUCTOR) continue;
                if(org.apache.commons.lang3.StringUtils.isNotEmpty(creator) && creator.equals(vo.getPkUser())){
                    result.put(keys[0], vo.getPkEnterprise());
                    result.put(keys[1], vo.getEnterpriseName());
                    break;
                }
            }
        }
        if(result.size() > 0){
            return result;
        }

        TeamEnterpriseRefVO[] teamEnterpriseRefVOS = enterpriseQuery.queryConstructionUnitInProject(pkProject);
        // 只有一个施工单位，直接带出
        if (ArrayUtils.isNotEmpty(teamEnterpriseRefVOS) && teamEnterpriseRefVOS.length == 1) {
            enterpriseInfoQuery.tranEntInfoField(teamEnterpriseRefVOS, new String[]{TeamEnterpriseVO.PK_ENTERPRISE}, new String[]{TeamEnterpriseVO.ENTERPRISE_NAME});
            result.put(keys[0], teamEnterpriseRefVOS[0].getPkEnterprise());
            result.put(keys[1], teamEnterpriseRefVOS[0].getEnterpriseName());
        }
        return result;
    }

    /**
     * 设置当前企业下成员的名称、手机和邮箱
     *
     * @param teamEnterpriseViewVO
     */
    private void setMembersInfo(TeamEnterpriseViewVO teamEnterpriseViewVO) {
        TeamMemberViewVO[] members = teamEnterpriseViewVO.getTeamMemberViewVOs();
        if (!StringUtils.isEmpty(members)) {

            Map<String, TeamMemberViewVO> memberViewVOMap = new HashMap<String, TeamMemberViewVO>();

            int i = 0;
            for (i = 0; i < members.length; i++) {
                memberViewVOMap.put(members[i].getPkUser(), members[i]);
            }
            UserInfo[] users = userInfoQuery.queryUsers(memberViewVOMap.keySet().toArray(new String[0]));
            if (!StringUtils.isEmpty(users)) {
                for (TeamMemberViewVO teamMemberViewVO : members) {

                    for (UserInfo userInfo : users) {
                        if (teamMemberViewVO.getPkUser().equals(userInfo.getUserId())) {
                            teamMemberViewVO.setUserName(userInfo.getUserName());
                            teamMemberViewVO.setPhoneNo(userInfo.getUserMobile());
                            teamMemberViewVO.setEmail(userInfo.getUserEmail());
                            break;
                        }
                    }
                }
            }
        }
    }

    @Getter
    @Setter
    private static class MemberAddVO {
        private String projectId;
        private String entId;
        private String[] users;
    }

}
